# plugs/hexonjoin.py
#
#

""" do a hex2ip lookup on JOIN. """

__status__ = "seen"

## gozerbot commands

from gozerbot.callbacks import callbacks
from gozerbot.persist.persistconfig import PersistConfig
from gozerbot.aliases import aliasset
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
from gozerbot.tests import tests

## basic imports

import struct
import socket

## plughelp

plughelp.add('hexjoin', 'show ip and hostname from user joining a channel')

## defines

cfg = PersistConfig()
cfg.define('channels', [])

## hexjoin callback

def hexjoin(bot, ievent):
    """ do a hex2ip lookup. """
    what = ievent.user
    ip = None
    try:
        ipint = int(what, 16)
        ipint = socket.ntohl(ipint)
        packed = struct.pack('l', ipint)
        ip = socket.inet_ntoa(str(packed))
    except Exception, ex: return
    try: hostname = socket.gethostbyaddr(ip)[0]
    except:
        if ip: bot.say(ievent.channel, '%s is on %s' % (ievent.nick, ip)) ; return
    bot.say(ievent.channel, '%s is on %s' % (ievent.nick, hostname))

## prehexjoin precondition

def prehexjoin(bot , ievent):
    """ check whether hexjoin callbacks should be called. """
    if not len(ievent.user) == 8: return 0
    try: int(ievent.user, 16)
    except ValueError: return 0
    if (bot.name, ievent.channel) in cfg.get('channels'): return 1

callbacks.add('JOIN', hexjoin, prehexjoin)

## hexjoin-enable command

def handle_hexjoinenable(bot, ievent):
    """ enable hexjoin lookups. """
    cfg.append('channels', (bot.name, ievent.channel))
    ievent.reply('%s channel added' % ievent.channel)

cmnds.add('hexjoin-enable', handle_hexjoinenable, 'OPER')
examples.add('hexjoin-enable', 'enable hexjoin in the channel the command is given in', 'hexjoin-enable')
tests.add('hexjoin-enable', 'channel added')

## hexjoin-disable command

def handle_hexjoindisable(bot, ievent):
    """ disable hexjoin lookups. """
    try:
        cfg.remove('channels', (bot.name, ievent.channel))
        ievent.reply('%s channel removed' % ievent.channel)
    except ValueError: ievent.reply('%s channel is not in channels list' % ievent.channel)

cmnds.add('hexjoin-disable', handle_hexjoindisable, 'OPER')
examples.add('hexjoin-disable', 'disable hexjoin in the channel this command is given in', 'hexjoin-disable')
tests.add('hexjoin-disable', 'channel')

#### BHJTW 22-01-2012
